package com.biubiu.firefly.wallpaper.box

import android.graphics.Bitmap
import com.biubiu.firefly.Constant
import org.jbox2d.collision.shapes.CircleShape
import org.jbox2d.collision.shapes.EdgeShape
import org.jbox2d.common.Vec2
import org.jbox2d.dynamics.BodyDef
import org.jbox2d.dynamics.BodyType
import org.jbox2d.dynamics.FixtureDef
import org.jbox2d.dynamics.World

object Box2DUtil {

    fun initEdges(
        w: Float,
        h: Float,
        world: World
    ) {
        // 创建边界
        val edgeList=  listOf(
            Vec2(0f,0f),
            Vec2(switchPositionToBody(w), 0f),
            Vec2(switchPositionToBody(w), switchPositionToBody(h)),
            Vec2(0f, switchPositionToBody(h))
        )

        for (i in 0..3) {
            val bodyDef = BodyDef()
            bodyDef.type = BodyType.STATIC
            val body = world.createBody(bodyDef)
            val boxShape = EdgeShape()
            boxShape.set(edgeList[i], edgeList[(i+1)%4])
            val fixtureDef = FixtureDef()
            fixtureDef.shape = boxShape
            fixtureDef.density = 0.8f
            fixtureDef.restitution = 0.6f
            body.createFixture(fixtureDef)
        }
    }

    fun createBody(
        cx: Float,
        cy: Float,
        vx: Float, //x轴矢量速度
        vy: Float, //y轴矢量速度
        radius: Float, //圆半径
        world: World,// 物理世界
        color: Int,
        stickers: Bitmap
    ): MyCircleColor {
        val bodyDef = BodyDef()
        bodyDef.type = BodyType.DYNAMIC //动态刚体
        bodyDef.position = Vec2(switchPositionToBody(cx), switchPositionToBody(cy))
        bodyDef.linearVelocity = Vec2(switchPositionToBody(vx), switchPositionToBody(vy))
        val circleShape = CircleShape()
        circleShape.radius = switchPositionToBody(radius)
        val ballFixtureDef = FixtureDef()
        ballFixtureDef.shape = circleShape
        ballFixtureDef.density = 1f
        ballFixtureDef.friction = 0.8f //摩擦力系数
        ballFixtureDef.restitution = 0.6f //弹性系数

        val ballBody = world.createBody(bodyDef) //刚体加载到物理世界
        ballBody.createFixture(ballFixtureDef) //刚体加载物理属性
        return MyCircleColor(
            ballBody,
            radius,
            color,
            stickers
        )
    }

    //view坐标映射为物理的坐标
    fun switchPositionToBody(viewPosition: Float): Float {
        return viewPosition / Constant.PROPORTION
    }

    //物理的坐标映射为view坐标
    fun switchPositionToView(bodyPosition: Float): Float {
        return bodyPosition * Constant.PROPORTION
    }
}